<?php
session_start();
require_once "include/database.php";
$db = db_connect();
require_once "include/auth.php";
$current_user = current_user();
require_login();
require_user(0);

$selected_courses = $_POST['courses'];

if (is_null($selected_courses) || empty($selected_courses)) {
    header("Location: registercourse.php?error=1");
    exit("You must select a course.");
}
else {
  include "_header.php";
  echo "<div class='container'>";
  echo "<table class='table table-bordered'>";
  echo "<h2 style='text-align:center;'> Registration Complete </h2>";
  echo "<thead style='background-color:darkgrey'><tr>" .
  "<td>Course Code</td>" .
  "<td>Title</td>" . 
  "<td>Section</td>" . 
  "<td>Mode of Grading</td>" .
  "</tr></thead>";

  $query = $db->prepare("INSERT INTO registers (Student_ID, CRN, Grade_Mode, Grade_Received) VALUES (:studentid, :crn, :grade_mode, NULL)");
  // Create the insert course statement for the database.
  foreach ($selected_courses as $course) {
    // Insert the course into the database.
    $success = true;
    if (!$query->execute(array('studentid' => $current_user['studentid'],
                               'crn' => $course,
                               'grade_mode' => $_POST['g' . $course]))) {
      $success = false;
    };
   
    $obtainclassquery = $db->prepare("SELECT Code, Title, Section FROM SectionComplete WHERE CRN=:crn");
    $obtainclassquery->execute(array("crn" => $course));
    $result = $obtainclassquery->fetch();

    if ($success) {
      echo "<tr class='success'>";
      echo "<td>" . $result['Code'] . "</td>" .
           "<td>" . $result['Title'] . "</td>" .
           "<td>" . $result['Section'] . "</td>" .
           "<td>" . $_POST['g' . $course] . "</td>";
      echo "</tr>";
    } else {
      echo "<tr class='error'>";
      echo "<td>" . $result['Code'] . "</td>" .
           "<td>" . $result['Title'] . " (ALREADY ADDED)</td>" .
           "<td>" . $result['Section'] . "</td>" .
           "<td>" . $_POST['g' . $course] . "</td>";
      echo "</tr>";
    }
  }
  echo "</div>";
}

?>